package session;

import java.io.Serializable;
import java.util.Collection;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import com.sina.sae.memcached.SaeMemcache;

public class SaeSessionDAO extends AbstractSessionDAO {
	
	private static final Logger log = LoggerFactory.getLogger(SaeSessionDAO.class);

	private SaeMemcache cache;

	public SaeSessionDAO() {
	        this.cache = new SaeMemcache("127.0.0.1", 11211);
	        this.cache.init();
	}


	@Override
	protected Serializable doCreate(Session session) {
		// TODO 自动生成方法存根
		Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        storeSession(sessionId, session);
        return sessionId;

	}
	
	protected Session storeSession(Serializable id, Session session) {
	        if (id == null) {
	            throw new NullPointerException("id argument cannot be null.");
	        }

	        boolean success = cache.set("saememcache" + session.getId().toString(), session, 36000);
	        System.out.println("storeSession session.getId().toString() =" + session.getId().toString() );
	        
	        if ( success = true) {
	        	System.out.println("set session to memcache success");
	        	return session;
	        } else return null;
	 }



	@Override
	protected Session doReadSession(Serializable sessionId) {
		// TODO 自动生成方法存根
        try {
        	System.out.println("doReadSession sessionId.toString() =" + sessionId.toString() );
            return cache.get("saememcache" + sessionId.toString());
//            String json = cache.get(MemcachedObjectType.SESSION.getPrefix() + sessionId.toString());
            //return (Session) serializer.deserialize(Encodes.decodeHex(json));
        } catch (Exception e) {
        	System.out.println("doReadSession can't get sessionId.toString() =" + sessionId.toString() );
            log.warn("## Not found session #{}", sessionId.toString());
            return null;
        }

	}

	public void delete(Session session) {
        if (session == null) {
            throw new NullPointerException("session argument cannot be null.");
        }
        Serializable id = session.getId();
        if (id != null) {
            cache.delete( "saememcache" + session.getId().toString());
        }



	}

	public Collection<Session> getActiveSessions() {
		// TODO 自动生成方法存根
		return null;

	}

	public void update(Session session) throws UnknownSessionException {
		// TODO 自动生成方法存根
		storeSession(session.getId(), session);
	}

}
